package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMapLoadedListener;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.PoiItem;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import java.io.File;
import java.util.List;

public class LocationFragment extends BaseFragment
    implements OnMapLoadedListener, OnInfoWindowClickListener {
  public static final String EXTRA_NAME = "com.isunland.managesystem.ui.EXTRA_NAME";
  private static final int REQUEST_ROUTE = 0;
  private MapView mapView;
  private AMap aMap;
  private PoiItem mPoiItem;
  private LatLng latLng;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.locationInfo);
    mPoiItem = getArguments().getParcelable(EXTRA_NAME);
    if (mPoiItem != null) {
      latLng = new LatLng(mPoiItem.getLatLonPoint().getLatitude(),
          mPoiItem.getLatLonPoint().getLongitude());
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_location, container, false);
    mapView = (MapView) v.findViewById(R.id.map);
    mapView.onCreate(savedInstanceState);
    //        if (aMap == null) {
    //            aMap = mapView.getMap();
    //            aMap.setOnMapLoadedListener(this);
    //            aMap.setOnInfoWindowClickListener(this);
    //            // 清理之前的图标
    //            aMap.clear();
    //            ArrayList<PoiItem> poiItems = new ArrayList<>();
    //            poiItems.add(mPoiItem);
    //            // 创建Poi图层
    //            PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
    //            // 去掉PoiOverlay上所有的Marker。
    //            poiOverlay.removeFromMap();
    //            // 添加Marker到地图中。
    //            poiOverlay.addToMap();
    //            // 移动镜头到当前的视角。
    //            poiOverlay.zoomToSpan();
    //        }
    //        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));

    if (aMap == null) {
      aMap = mapView.getMap();
    }
    Marker marker = aMap.addMarker(new MarkerOptions().position(latLng));
    CameraUpdate cameraUpdate =
        CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng,//新的中心点坐标
            15, //新的缩放级别
            0, //俯仰角0°~45°（垂直与地图时为0）
            0  ////偏航角 0~360° (正北方为0)
        ));
    aMap.animateCamera(cameraUpdate);
    marker.showInfoWindow();
    return v;
  }

  /**
   * 方法必须重写
   */
  @Override public void onResume() {
    super.onResume();
    mapView.onResume();
  }

  /**
   * 方法必须重写
   */
  @Override public void onPause() {
    super.onPause();
    mapView.onPause();
  }

  /**
   * 方法必须重写
   */
  @Override public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
  }

  /**
   * 方法必须重写
   */
  @Override public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_navigation, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        getActivity().finish();

        return true;
      case R.id.menu_item_navigation:
        showDialogRoute();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  public static Fragment newInstance(PoiItem item) {
    Bundle argBundle = new Bundle();
    argBundle.putParcelable(EXTRA_NAME, item);
    Fragment fragment = new LocationFragment();
    fragment.setArguments(argBundle);
    return fragment;
  }

  /**
   * 显示标记marker的信息窗口infoWindow
   */
  @Override public void onMapLoaded() {
    List<Marker> list = aMap.getMapScreenMarkers();
    if (list != null && list.size() > 0) {
      for (int i = 0; i < list.size(); i++) {
        list.get(i).showInfoWindow();
      }
    }
  }

  @Override public void onInfoWindowClick(Marker arg0) {
    //		route();
    showDialogRoute();
  }

  /**
   * 显示导航对话框
   */
  private void showDialogRoute() {

    FragmentManager fm = getActivity().getSupportFragmentManager();

    BaseConfirmDialogFragment dialog = BaseConfirmDialogFragment.newInstance(R.string.routeConfirm);
    dialog.setTargetFragment(LocationFragment.this, REQUEST_ROUTE);
    dialog.show(fm, "");
  }

  /**
   * 导航
   */
  private void route() {
    double latitude = mPoiItem.getLatLonPoint().getLatitude();
    double longitudde = mPoiItem.getLatLonPoint().getLongitude();

    Intent intent = new Intent();
    // 导航
    intent.setData(Uri.parse("androidamap://route?sourceApplication=国欣ERP+"
        + " &dlat="
        + latitude
        + "&dlon="
        + longitudde
        + "&dname="
        + mPoiItem.getTitle()
        + "&dev=0&m=0&t=1&showType=1"));

    if (isInstallByread("com.autonavi.minimap")) {
      startActivity(intent);
    } else {
      Toast.makeText(getActivity(), R.string.notFoundGaoDe, Toast.LENGTH_SHORT).show();
    }
  }

  // 判断是否安装目标应用
  @SuppressLint("SdCardPath") private boolean isInstallByread(String packageName) {
    return new File("/data/data/" + packageName).exists();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    route();
    super.onActivityResult(requestCode, resultCode, data);
  }
}
